package com.ushio.capsuleservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ushio.capsuleservice.model.dto.ApiResponse;
import com.ushio.capsuleservice.model.entity.Container;
import com.ushio.capsuleservice.model.entity.Plan;
import com.ushio.capsuleservice.service.ContainerService;
import com.ushio.capsuleservice.service.PlanService;
// TODO: 后续加上用户登录后，解注释以下代码
// import com.ushio.capsuleservice.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 计划控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/plans")
@CrossOrigin(origins = "*")
public class PlanController {

    @Autowired
    private PlanService planService;

    @Autowired
    private ContainerService containerService;

    // TODO: 后续加上用户登录后，解注释以下代码
    // @Autowired
    // private JwtUtil jwtUtil;

    /**
     * 获取计划列表
     */
    @GetMapping
    public ApiResponse<List<Plan>> getPlans(HttpServletRequest request) {
        try {
            // TODO: 后续加上用户登录后，解注释以下代码
            // String token = getTokenFromRequest(request);
            // Long userId = jwtUtil.getUserIdFromToken(token);

            // 暂时使用默认用户ID = 1
            Long userId = 1L;

            List<Plan> plans = planService.getPlansByUserId(userId);
            return ApiResponse.success("获取计划列表成功", plans);
        } catch (Exception e) {
            log.error("获取计划列表失败", e);
            return ApiResponse.error(500, "获取计划列表失败");
        }
    }


    /**
     * 创建新计划
     */
    @PostMapping
    public ApiResponse<Map<String, Object>> createPlan(@RequestBody Plan plan, HttpServletRequest request) {
        try {
            // 参数验证
            if (plan.getTitle() == null || plan.getTitle().trim().isEmpty()) {
                return ApiResponse.error(400, "计划创建失败：标题不能为空");
            }

            // TODO: 后续加上用户登录后，解注释以下代码
            // String token = getTokenFromRequest(request);
            // Long userId = jwtUtil.getUserIdFromToken(token);

            // 暂时使用默认用户ID = 1
            Long userId = 1L;
            plan.setUserId(userId);

            Plan createdPlan = planService.createPlan(plan);

            Map<String, Object> data = new HashMap<>();
            data.put("id", createdPlan.getId().toString());

            return ApiResponse.success("计划创建成功", data);
        } catch (Exception e) {
            log.error("创建计划失败", e);
            return ApiResponse.error(400, "计划创建失败：" + e.getMessage());
        }
    }

    /**
     * 更新计划
     */
    @PutMapping("/{planId}")
    public ApiResponse<String> updatePlan(@PathVariable Long planId, @RequestBody Plan plan, HttpServletRequest request) {
        try {
            // TODO: 后续加上用户登录后，解注释以下代码
            // String token = getTokenFromRequest(request);
            // Long userId = jwtUtil.getUserIdFromToken(token);

            // 暂时使用默认用户ID = 1
            Long userId = 1L;

            // 检查计划是否存在且属于当前用户
            LambdaQueryWrapper<Plan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Plan::getId, planId);
            Plan existingPlan = planService.getOne(queryWrapper);
            if (existingPlan == null) {
                return ApiResponse.error(404, "计划不存在");
            }
            // TODO: 后续加上用户登录后，解注释以下代码
            // if (!existingPlan.getUserId().equals(userId)) {
            //     return ApiResponse.error(403, "无权限修改此计划");
            // }

            planService.updatePlan(planId, plan);
            return ApiResponse.success("计划更新成功", null);
        } catch (Exception e) {
            log.error("更新计划失败", e);
            if (e.getMessage().contains("计划不存在")) {
                return ApiResponse.error(404, "计划不存在");
            }
            return ApiResponse.error(500, "计划更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除计划
     */
    @DeleteMapping("/{planId}")
    public ApiResponse<String> deletePlan(@PathVariable Long planId, HttpServletRequest request) {
        try {
            // TODO: 后续加上用户登录后，解注释以下代码
            // String token = getTokenFromRequest(request);
            // Long userId = jwtUtil.getUserIdFromToken(token);

            // 暂时使用默认用户ID = 1
            Long userId = 1L;

            // 检查计划是否存在且属于当前用户
            LambdaQueryWrapper<Plan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Plan::getId, planId);
            Plan existingPlan = planService.getOne(queryWrapper);
            if (existingPlan == null) {
                return ApiResponse.error(404, "计划不存在");
            }
            // TODO: 后续加上用户登录后，解注释以下代码
            // if (!existingPlan.getUserId().equals(userId)) {
            //     return ApiResponse.error(403, "无权限删除此计划");
            // }

            boolean success = planService.deletePlan(planId);
            if (success) {
                return ApiResponse.success("计划删除成功", null);
            } else {
                return ApiResponse.error(500, "计划删除失败");
            }
        } catch (Exception e) {
            log.error("删除计划失败", e);
            if (e.getMessage().contains("计划不存在")) {
                return ApiResponse.error(404, "计划不存在");
            }
            return ApiResponse.error(500, "计划删除失败：" + e.getMessage());
        }
    }

    /**
     * 创建并绑定容器到计划
     */
    @PostMapping("/{planId}/containers")
    public ApiResponse<Long> bindContainer(@PathVariable Long planId,@RequestBody Container container, HttpServletRequest request) {
        // TODO: 后续加上用户登录后，解注释以下代码
        // String token = getTokenFromRequest(request);
        // Long userId = jwtUtil.getUserIdFromToken(token);

        //todo  暂时使用默认用户ID = 1
        Long userId = 1L;
        container.setUserId(userId);

        // 设置必要的默认值
        LocalDateTime now = LocalDateTime.now();
        container.setStartTime(now); // 开始时间设为当前时间
        container.setCreatedTime(now); // 创建时间设为当前时间
        container.setUpdatedTime(now); // 更新时间设为当前时间

        // 如果 status 为空，设置默认值
        if (container.getStatus() == null) {
            container.setStatus(1); // 1-进行中
        }

        // 如果 elapsedTime 为空，设置默认值
        if (container.getElapsedTime() == null) {
            container.setElapsedTime(0);
        }

        // 如果 tags 为 null，设置为空字符串
        if (container.getTags() == null) {
            container.setTags("");
        }

        // 检查计划是否存在且属于当前用户
        LambdaQueryWrapper<Plan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Plan::getId, planId);
        Plan existingPlan = planService.getOne(queryWrapper);

        if (existingPlan == null) {
            return ApiResponse.error(404, "计划不存在");
        }
        // TODO: 后续加上用户登录后，解注释以下代码
        // if (!existingPlan.getUserId().equals(userId)) {
        //     return ApiResponse.error(403, "无权限操作此计划");
        // }

        //todo 比这个if else更优雅的写法？
        Long containerId = 0L;
        //(创建并绑定)如果没有就创建一个todo
        boolean save = containerService.save(container);
        if (save) {
            boolean success = planService.bindContainer(planId, container.getId());
            if (success) {
                return ApiResponse.success("容器绑定成功", container.getId());
            }
            return ApiResponse.error(500,"绑定容器失败");
        } else {
            //创建容器失败
            return ApiResponse.error(500, "创建容器失败");
        }

    }

    /**
     * 解绑计划中的容器
     */
    @DeleteMapping("/{planId}/containers/{containerId}")
    public ApiResponse<String> unbindContainer(@PathVariable Long planId, @PathVariable Long containerId, HttpServletRequest request) {
        try {
            // TODO: 后续加上用户登录后，解注释以下代码
            // String token = getTokenFromRequest(request);
            // Long userId = jwtUtil.getUserIdFromToken(token);

            // 暂时使用默认用户ID = 1
            Long userId = 1L;

            // 检查计划是否存在且属于当前用户
            LambdaQueryWrapper<Plan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Plan::getId, planId);
            Plan existingPlan = planService.getOne(queryWrapper);
            if (existingPlan == null) {
                return ApiResponse.error(404, "计划不存在");
            }
            // TODO: 后续加上用户登录后，解注释以下代码
            // if (!existingPlan.getUserId().equals(userId)) {
            //     return ApiResponse.error(403, "无权限操作此计划");
            // }

            boolean success = planService.unbindContainer(planId, containerId);
            if (success) {
                return ApiResponse.success("容器解绑成功", null);
            } else {
                return ApiResponse.error(500, "容器解绑失败");
            }
        } catch (Exception e) {
            log.error("解绑容器失败", e);
            if (e.getMessage().contains("绑定关系不存在")) {
                return ApiResponse.error(404, "绑定关系不存在");
            }
            return ApiResponse.error(500, "容器解绑失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新计划
     */
    @PutMapping("/batch")
    public ApiResponse<String> batchUpdatePlans(@RequestBody Map<String, List<Plan>> requestBody, HttpServletRequest request) {
        try {
            // TODO: 后续加上用户登录后，解注释以下代码
            // String token = getTokenFromRequest(request);
            // Long userId = jwtUtil.getUserIdFromToken(token);

            // 暂时使用默认用户ID = 1
            Long userId = 1L;

            List<Plan> plans = requestBody.get("data");
            if (plans == null || plans.isEmpty()) {
                return ApiResponse.error(400, "更新数据不能为空");
            }

            // 验证所有计划都属于当前用户
            for (Plan plan : plans) {
                if (plan.getId() == null) {
                    return ApiResponse.error(400, "计划ID不能为空");
                }

                LambdaQueryWrapper<Plan> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Plan::getId, plan.getId());
                Plan existingPlan = planService.getOne(queryWrapper);
                if (existingPlan == null) {
                    return ApiResponse.error(404, "计划不存在：" + plan.getId());
                }
                // TODO: 后续加上用户登录后，解注释以下代码
                // if (!existingPlan.getUserId().equals(userId)) {
                //     return ApiResponse.error(403, "无权限修改计划：" + plan.getId());
                // }
            }

            boolean success = planService.batchUpdatePlans(plans);
            if (success) {
                return ApiResponse.success("批量更新成功", null);
            } else {
                return ApiResponse.error(500, "批量更新失败");
            }
        } catch (Exception e) {
            log.error("批量更新计划失败", e);
            return ApiResponse.error(500, "批量更新失败：" + e.getMessage());
        }
    }

    /**
     * 获取某个计划的绑定容器列表
     */
    @GetMapping("/{planId}/containers")
    public ApiResponse<List<Map<String, Object>>> getPlanContainers(@PathVariable Long planId, HttpServletRequest request) {
        try {
            // TODO: 后续加上用户登录后，解注释以下代码
            // String token = getTokenFromRequest(request);
            // Long userId = jwtUtil.getUserIdFromToken(token);

            // 暂时使用默认用户ID = 1
            Long userId = 1L;

            // 检查计划是否存在且属于当前用户
            LambdaQueryWrapper<Plan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Plan::getId, planId);
            Plan existingPlan = planService.getOne(queryWrapper);
            if (existingPlan == null) {
                return ApiResponse.error(404, "计划不存在");
            }
            // TODO: 后续加上用户登录后，解注释以下代码
            // if (!existingPlan.getUserId().equals(userId)) {
            //     return ApiResponse.error(403, "无权限查看此计划");
            // }

            // 获取计划绑定的容器列表
            List<Container> containers = containerService.getContainersByPlanId(planId);

            // 转换为前端需要的格式
            List<Map<String, Object>> containerList = containers.stream().map(container -> {
                Map<String, Object> containerMap = new HashMap<>();
                containerMap.put("id", container.getId().toString());
                containerMap.put("title", container.getTitle());
                containerMap.put("description", container.getDescription());
                containerMap.put("category", container.getCategory());

                // 计算预估时间（分钟）
                int estimatedTime = 0;
                if (container.getStartTime() != null && container.getEndTime() != null) {
                    long diffInMillis = Duration.between(container.getStartTime(), container.getEndTime()).toMillis();
                    estimatedTime = (int) (diffInMillis / (1000 * 60)); // 转换为分钟
                }
                containerMap.put("estimatedTime", estimatedTime);

                containerMap.put("startTime", container.getStartTime() != null ? container.getStartTime().toString() : null);
                containerMap.put("endTime", container.getEndTime() != null ? container.getEndTime().toString() : null);

                // 实际时间（分钟）
                int actualTime = container.getElapsedTime() != null ? container.getElapsedTime() / 60 : 0;
                containerMap.put("actualTime", actualTime);

                // 状态转换
                String status = "pending";
                if (container.getStatus() != null) {
                    switch (container.getStatus()) {
                        case 1:
                            status = "in-progress";
                            break;
                        case 2:
                            status = "completed";
                            break;
                        default:
                            status = "pending";
                    }
                }
                containerMap.put("status", status);

                // 评价信息
                Map<String, Object> evaluation = new HashMap<>();
                evaluation.put("effectivenessScore", container.getEffectivenessScore() != null ? container.getEffectivenessScore().intValue() : 0);

                // 解析标签
                List<String> positiveTags = new ArrayList<>();
                List<String> negativeTags = new ArrayList<>();
                if (container.getTags() != null && !container.getTags().isEmpty()) {
                    String[] tags = container.getTags().split(",");
                    for (String tag : tags) {
                        tag = tag.trim();
                        if (tag.startsWith("#")) {
                            positiveTags.add(tag);
                        } else {
                            negativeTags.add(tag);
                        }
                    }
                }
                evaluation.put("positiveTags", positiveTags);
                evaluation.put("negativeTags", negativeTags);
                evaluation.put("notes", ""); // 可以根据需要添加备注字段

                containerMap.put("evaluation", evaluation);
                containerMap.put("createdTime", container.getCreatedTime() != null ? container.getCreatedTime().toString() : null);
                containerMap.put("updatedTime", container.getUpdatedTime() != null ? container.getUpdatedTime().toString() : null);

                return containerMap;
            }).collect(Collectors.toList());

            return ApiResponse.success("获取计划容器列表成功", containerList);
        } catch (Exception e) {
            log.error("获取计划容器列表失败", e);
            if (e.getMessage().contains("计划不存在")) {
                return ApiResponse.error(404, "计划不存在");
            }
            return ApiResponse.error(500, "获取计划容器列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取容器列表（用于计划绑定）
     */
    @GetMapping("/plan/time_capsule_containers")
    public ApiResponse<Map<String, Object>> getTimeCapsuleContainers(HttpServletRequest request) {
        try {
            // TODO: 后续加上用户登录后，解注释以下代码
            // String token = getTokenFromRequest(request);
            // Long userId = jwtUtil.getUserIdFromToken(token);

            // 暂时使用默认用户ID = 1
            Long userId = 1L;

            // 获取用户的所有容器
            List<Container> allContainers = containerService.findByUserId(userId);

            // 过滤掉已删除的容器
            List<Container> containers = allContainers.stream()
                    .filter(container -> container.getStatus() != 0)
                    .collect(Collectors.toList());

            // 转换为前端需要的格式
            List<Map<String, Object>> containerList = containers.stream().map(container -> {
                Map<String, Object> containerMap = new HashMap<>();
                containerMap.put("id", container.getId().toString());
                containerMap.put("title", container.getTitle());
                containerMap.put("description", container.getDescription());
                containerMap.put("category", container.getCategory());

                // 计算预估时间（分钟）
                int estimatedTime = 0;
                if (container.getStartTime() != null && container.getEndTime() != null) {
                    long diffInMillis = Duration.between(container.getStartTime(), container.getEndTime()).toMillis();
                    estimatedTime = (int) (diffInMillis / (1000 * 60)); // 转换为分钟
                }
                containerMap.put("estimatedTime", estimatedTime);

                containerMap.put("startTime", container.getStartTime() != null ? container.getStartTime().toString() : null);
                containerMap.put("endTime", container.getEndTime() != null ? container.getEndTime().toString() : null);

                // 实际时间（分钟）
                int actualTime = container.getElapsedTime() != null ? container.getElapsedTime() / 60 : 0;
                containerMap.put("actualTime", actualTime);

                // 状态转换
                String status = "pending";
                if (container.getStatus() != null) {
                    switch (container.getStatus()) {
                        case 1:
                            status = "in-progress";
                            break;
                        case 2:
                            status = "completed";
                            break;
                        default:
                            status = "pending";
                    }
                }
                containerMap.put("status", status);

                // 评价信息
                Map<String, Object> evaluation = new HashMap<>();
                evaluation.put("effectivenessScore", container.getEffectivenessScore() != null ? container.getEffectivenessScore().intValue() : 0);

                // 解析标签
                List<String> positiveTags = new ArrayList<>();
                List<String> negativeTags = new ArrayList<>();
                if (container.getTags() != null && !container.getTags().isEmpty()) {
                    String[] tags = container.getTags().split(",");
                    for (String tag : tags) {
                        tag = tag.trim();
                        if (tag.startsWith("#")) {
                            positiveTags.add(tag);
                        } else {
                            negativeTags.add(tag);
                        }
                    }
                }
                evaluation.put("positiveTags", positiveTags);
                evaluation.put("negativeTags", negativeTags);
                evaluation.put("notes", ""); // 可以根据需要添加备注字段

                containerMap.put("evaluation", evaluation);

                return containerMap;
            }).collect(Collectors.toList());

            // 查找当前活跃的容器
            String activeContainerId = null;
            for (Container container : containers) {
                if (container.getStatus() == 1) { // 进行中状态
                    activeContainerId = container.getId().toString();
                    break;
                }
            }

            Map<String, Object> data = new HashMap<>();
            data.put("containers", containerList);
            data.put("activeContainerId", activeContainerId);

            return ApiResponse.success(data);
        } catch (Exception e) {
            log.error("获取容器列表失败", e);
            return ApiResponse.error("获取容器列表失败：" + e.getMessage());
        }
    }

    // TODO: 后续加上用户登录后，解注释以下代码
    // /**
    //  * 从请求中获取token
    //  */
    // private String getTokenFromRequest(HttpServletRequest request) {
    //     String bearerToken = request.getHeader("Authorization");
    //     if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
    //         return bearerToken.substring(7);
    //     }
    //     throw new RuntimeException("未找到有效的token");
    // }
}